<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | 企业管理相关Controller v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-08-09
// +-------------------------------------------------------------------------------

namespace app\core\controller\site;

use app\core\model\CacheKey;
use app\core\model\Enterprise;
use app\core\model\EnterpriseModule;
use app\core\model\SiteConfig;
use app\core\model\SiteModule;
use common\Encryption;
use ding\ApiHelper;
use ding\model\MediaTypeEnum;
use ding\request\MicroappSaveRequest;
use think\Config;
use think\Cookie;

class EnterpriseMicroappController extends SiteBaseController {

    /**
     * 微应用管理
     *
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function all() {
        $eid = input("param.eid");

        $enterprise = Enterprise::get($eid);
        if (empty($enterprise)) {
            $this->error("参数错误，找不到该企业");
        }

        list($globalMicroapp, $microapps) = $this->_getMicroapp($enterprise, true);

        if (!$globalMicroapp) {
            $globalAgentId = false;
            $globalMicroapp = [
                'name' => mb_substr(SiteConfig::get(SiteConfig::SITE_NAME), 0, 10, "utf-8"),
                'appDesc' => mb_substr(SiteConfig::get(SiteConfig::SITE_SLOGAN), 0, 20, "utf-8"),
                'appIcon' => '/static/images/slogo.png',
                'ompLink' => request()->domain() . "/core/enterprise?eid=" . $enterprise['id'],
                'homepageLink' => request()->domain() . "/core/enterprise.index/microapp?eid=" . $enterprise['id'],
                'pcHomepageLink' => request()->domain() . "/core/enterprise.index/microapp?eid=" . $enterprise['id']
            ];
        } else {
            $globalAgentId = $enterprise['agent_id'];
        }

        $this->assign("globalAgentId", $globalAgentId);
        $this->assign("globalMicroapp", $globalMicroapp);
        $this->assign("microapps", $microapps);
        $this->assign("eid", $eid);
        return view();
    }

    /**
     * 删除全局微应用
     *
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function delGlobalMicroapp() {
        $eid = input("param.eid");

        $enterprise = Enterprise::get($eid);
        if (empty($enterprise)) {
            $this->error("参数错误，找不到该企业");
        }
        if (empty($enterprise['agent_id'])) {
            $this->error("无需删除，该企业没有生成全局微应用");
        }

        $apiHelper = new ApiHelper($enterprise, null);
        $agentId = $enterprise['agent_id'];
        $ret = $apiHelper->microappDelete($agentId);
        if ($ret) {
            Enterprise::update([
                'agent_id' => ''
            ], $eid);
            $this->success("删除成功");
        } else {
            $this->error("删除失败：" . $apiHelper->getLastStatusMsg());
        }
    }

    /**
     * 更新全局微应用
     *
     * @throws \ReflectionException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function updateGlobalMicroapp() {
        $eid = input("param.eid");

        $enterprise = Enterprise::get($eid);
        if (empty($enterprise)) {
            $this->error("参数错误，找不到该企业");
        }

        $apiHelper = new ApiHelper($enterprise, null);

        $appIcon = input("post.appIcon");
        $appName = input("post.name");
        $appDesc = input("post.appDesc");
        $homepageUrl = input("post.homepageLink");
        $pcHomepageUrl = input("post.pcHomepageLink");
        $ompLink = input("post.ompLink");
        if (!startsWith($appIcon, "http://") && !startsWith($appIcon, "https://")) {
            $appIcon = realpath(APP_PATH . "../public" . $appIcon);
            $response = $apiHelper->mediaUpload($appIcon, MediaTypeEnum::IMAGE);
            $appIcon = fetch($response, "media_id");
        } else {
            $microapp = self::_getMicroapp($enterprise);
            $appIcon = $microapp['appIcon'];
        }

        list($globalMicroapp, $microapps) = $this->_getMicroapp($enterprise, true);

        if (!$globalMicroapp) {
            //创建
            $request = MicroappSaveRequest::microappCreateRequest($appIcon, $appName, $appDesc, $homepageUrl)
                ->setPcHomepageUrl($pcHomepageUrl)->setOmpLink($ompLink);
            $response = $apiHelper->microappCreate($request);
            if (empty($response)) {
                $this->error("微应用创建失败：" . $apiHelper->getLastStatusMsg());
            }
            Enterprise::update([
                'agent_id' => $response
            ], $eid);
            $this->success("微应用创建成功");
        } else {
            //修改
            $request = MicroappSaveRequest::microappUpdateRequest($enterprise['agent_id'], $appIcon, $appName, $appDesc, $homepageUrl)
                ->setPcHomepageUrl($pcHomepageUrl)->setOmpLink($ompLink);
            $response = $apiHelper->microappUpdate($request);
            if (!$response) {
                $this->error("微应用更新失败：" . $apiHelper->getLastStatusMsg());
            }
            $this->success("微应用更新成功");
        }

    }

    /**
     * 删除自定义微应用
     *
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delCustomMicroapp() {
        $eid = input("param.eid");
        $agentId = input("param.agentId");

        $enterprise = Enterprise::get($eid);
        if (empty($enterprise)) {
            $this->error("参数错误，找不到该企业");
        }
        $apiHelper = new ApiHelper($enterprise, null);
        $ret = $apiHelper->microappDelete($agentId);
        if ($ret) {
            $this->success("删除成功");
        } else {
            $this->error("删除失败：" . $apiHelper->getLastStatusMsg());
        }
    }

    /**
     * @param $enterprise
     * @param $returnList
     * @return mixed
     * @throws \think\exception\DbException
     */
    private function _getMicroapp($enterprise, $returnList = false) {
        $globalMicroapp = false;
        $apiHelper = new ApiHelper($enterprise, null);
        $appList = $apiHelper->microappList();
        if (!empty($appList)) {
            foreach ($appList as $app) {
                if ($app['agentId'] == $enterprise['agent_id']) {
                    $globalMicroapp = $app;
                    break;
                }
            }
        }
        if ($returnList) {
            return [$globalMicroapp, $appList];
        }
        return $globalMicroapp;
    }
}
